package com.tg.base.concurrent.future;

import java.util.concurrent.*;

/**
 * Created by MagicBook on 2020/1/31.
 */
public class FutureTaskTest {
    public static void main(String[] args) throws Exception {

        callableExample();

//        runnableExample();
    }

    private static void runnableExample() throws Exception {
        String result = "";
        new Thread(new FutureTask<String>(() -> {
            System.out.println("正在执行FutureTask");
            threadSleep(100);

        }, result)).start();
    }

    private static void callableExample() throws Exception {
        FutureTask<String> futureTask1 = new FutureTask<String>(() -> {
            threadSleep(60 * 1000 * 5);
            return "1";
        });

        FutureTask<String> futureTask2 = new FutureTask<String>(() -> {
            threadSleep(100);
            return "2";
        });

        FutureTask<String> futureTask3 = new FutureTask<String>(() -> {
            threadSleep(600);
            return "3";
        });

        ExecutorService executor = Executors.newFixedThreadPool(3);
        executor.submit(futureTask1);
        executor.submit(futureTask2);
        executor.submit(futureTask3);

        if (futureTask1.isDone() && futureTask2.isDone() && futureTask3.isDone()) {
            System.out.println("Done");
            executor.shutdown();
            return;
        }
        if (!futureTask1.isDone()) {
            //get()阻塞等待结果
            System.out.println("Task1输出结果" + futureTask1.get());
        }

        if (futureTask2.isDone()) {
            //task2 100ms完成，先于task1完成，get()无阻塞
            System.out.println("Task2输出结果" + futureTask2.get());
        } else {
            System.out.println("等待Task2完成");
        }

        try {
            //task1跑了200ms，task3要跑600ms，设100ms超时t3仍然未能完成
            String s = futureTask3.get(100L, TimeUnit.MILLISECONDS);
            if (s != null) {
                System.out.println("Task3输出结果" + s);
            }
        } catch (TimeoutException ex) {
            System.out.println("Task3超时");
        }

        executor.shutdown();
    }

    private static void threadSleep(long ms) {
        try {
            TimeUnit.MILLISECONDS.sleep(ms);
        } catch (InterruptedException ex) {

        }
    }
}
